package com.junlong0716.enjoylearning.ui

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Color
import android.os.Bundle
import android.os.IBinder
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.blankj.utilcode.util.ToastUtils
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.ChannelViewpagerAdapter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.entity.ClassifyEntity
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.enjoylearning.service.MusicService
import com.junlong0716.enjoylearning.service.PlayerManager
import com.junlong0716.enjoylearning.widget.PlayerBarView
import com.junlong0716.module.common.base.BaseActivity
import com.junlong0716.module.common.constant.Constant
import com.junlong0716.module.common.event.AudioLayoutVisibleStateEvent
import com.junlong0716.module.common.rxbus.Subscribe
import com.junlong0716.module.common.rxbus.ThreadMode
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_channel.*
import kotlinx.android.synthetic.main.view_title_bar.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView
import org.json.JSONObject

class ChannelActivity : BaseActivity<ChannelPresenter>(), ChannelContract.View, View.OnClickListener {
    private var channelName = ""
    private var channelType = 1
    private lateinit var mTitleDataList: ArrayList<ClassifyEntity>
    private lateinit var commonNavigator: CommonNavigator
    private lateinit var channelDetailFragmentList: ArrayList<Fragment>
    private lateinit var channelViewpagerAdapter: ChannelViewpagerAdapter
    private var mPlayerBarView: PlayerBarView? = null
    private var musicService: MusicService? = null
    private var mPlayerManager: PlayerManager? = null


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBus(s: AudioLayoutVisibleStateEvent) {
        if (s.key == Constant.AUDIO_LAYOUT_VISIBLE_FLAG) {
            //先判断是否能显示播放控制bar
            if (mPlayerManager!!.getPlayerBarVisibilityState()) {
                if (s.isVisible) {
                    mPlayerBarView!!.setPlayerBarVisibility(true)
                } else {
                    mPlayerBarView!!.setPlayerBarVisibility(false)
                }
            }
        }
    }


    override fun beforeSetLayout() {
        channelName = intent.getStringExtra("CHANNEL_NAME")
        channelType = intent.getIntExtra("CHANNEL_TYPE", 1)
    }

    override fun attachPresenter() {
        mPresenter = ChannelPresenter()
        mPresenter!!.attachView(this)
    }

    override fun getLayoutId(): Int = R.layout.activity_channel

    override fun initView(savedInstanceState: Bundle?) {

        tv_title.text = channelName
        initListener()
        requestChannelType()
        mTitleDataList = ArrayList()
        commonNavigator = CommonNavigator(this)
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getTitleView(p0: Context?, p1: Int): IPagerTitleView {
                val colorTransitionPagerTitleView = ColorTransitionPagerTitleView(this@ChannelActivity)
                colorTransitionPagerTitleView.normalColor = Color.GRAY
                colorTransitionPagerTitleView.selectedColor = ContextCompat.getColor(this@ChannelActivity, R.color.colorAccent)
                colorTransitionPagerTitleView.text = mTitleDataList[p1].classifyName
                colorTransitionPagerTitleView.setOnClickListener {
                    view_pager.currentItem = p1
                }
                return colorTransitionPagerTitleView
            }

            override fun getCount(): Int = if (mTitleDataList == null) 0 else mTitleDataList.size

            override fun getIndicator(p0: Context?): IPagerIndicator {
                val indicator = LinePagerIndicator(this@ChannelActivity)
                indicator.lineHeight = 7f
                indicator.setColors(ContextCompat.getColor(this@ChannelActivity, R.color.colorAccent))
                indicator.mode = LinePagerIndicator.MODE_WRAP_CONTENT
                return indicator
            }
        }
        magic_indicator.navigator = commonNavigator
        ViewPagerHelper.bind(magic_indicator, view_pager)
        channelDetailFragmentList = ArrayList()
        channelViewpagerAdapter = ChannelViewpagerAdapter(supportFragmentManager, channelDetailFragmentList)
        view_pager.adapter = channelViewpagerAdapter
        view_pager.offscreenPageLimit = 3
    }


    private fun requestChannelType() {
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_CLASSIFY)
                .tag(this)
                .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                .cacheKey("CATCH_CLASSIFY")
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        setData(response!!.body())
                    }

                    override fun onCacheSuccess(response: Response<String>?) {
                        setData(response!!.body())
                    }

                    override fun onError(response: Response<String>?) {
                        ToastUtils.showShort("请求失败！")
                    }
                })
    }

    private fun setData(body: String?) {
        val jsonObject = JSONObject(body)
        val data = jsonObject.getJSONArray("data")
        val classifyData = ArrayList<ClassifyEntity>()
        val itemArrayAll = ArrayList<ClassifyEntity.DetailsBean>()
        classifyData.add(ClassifyEntity(0, "全部", itemArrayAll))
        for (i in 0 until data.length()) {
            val id = data.getJSONObject(i).getInt("id")
            val classifyName = data.getJSONObject(i).getString("classifyName")
            val details = data.getJSONObject(i).getJSONArray("details")
            val itemArray = ArrayList<ClassifyEntity.DetailsBean>()
            for (j in 0 until details.length()) {
                val id = details.getJSONObject(j).getInt("id")
                val classifyName = details.getJSONObject(j).getString("classifyName")
                itemArray.add(ClassifyEntity.DetailsBean(id, classifyName, false))
            }
            classifyData.add(ClassifyEntity(id, classifyName, itemArray))
        }

        for (i in 0 until classifyData.size) {
            mTitleDataList.add(classifyData[i])
            channelDetailFragmentList.add(ChannelDetailFragment.newInstance(channelType, classifyData[i].id))
        }
        channelViewpagerAdapter.notifyDataSetChanged()
        commonNavigator.notifyDataSetChanged()
    }

    private fun initListener() {
        rl_back.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.rl_back -> {
                finish()
            }
            else -> {
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mPlayerBarView = null
        unbindService(conn)
    }

    private var conn = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val myBinder = service as (MusicService.MyBinder)
            musicService = myBinder.getService()
            mPlayerManager = musicService!!.getPlayerManager()
            mPlayerBarView = PlayerBarView(this@ChannelActivity, mPlayerManager!!, rl_root)
        }
    }

    companion object {
        fun newInstance(context: Context, channelName: String, channelType: Int) {
            val intent = Intent(context, ChannelActivity::class.java)
            intent.putExtra("CHANNEL_NAME", channelName)
            intent.putExtra("CHANNEL_TYPE", channelType)
            context.startActivity(intent)
        }
    }


    override fun bindService() {
        val intent = Intent(this, MusicService::class.java)
        bindService(intent, conn, AppCompatActivity.BIND_AUTO_CREATE)
    }

    fun getPlayerManager(): PlayerManager {
        return mPlayerManager!!
    }
}
